%eyelink2_blink_remover
% this file removes blinks from london eye data and combines matlab timeing
% data with the eye tracker data in to one file (*B.mat)



clear;
clc;
close all;

scnsize = get(0,'ScreenSize');

redraw=0;
files = dir('*.eye'); % find all files with the eye extention
% data_list entries must be 8 characters long.(eyelink2 still lives in dos)
if length(files)==0
    disp(' ');
    disp('there are no *.eye files in current directory');
    cd;
    return
end
files.name;

for fp_num=1:length(files)
    eye_file=files(fp_num).name;
    mat_file=[eye_file(1:length(eye_file)-3) 'mat'];
    load(mat_file );
    fp = fopen(eye_file);
    if fp==-1
        error(['can not open ' eye_file]);
    end
    [time,x,y,size] = textread(eye_file,'%f %f %f %f');
    fclose(fp);
    
    
    
    if ~isfield(A,'screenRect')
        A.screenRect=[0 0 1152 864];
    end
    if ~isfield(A,'pixperdeg')
        A.pixperdeg=19;
    end
    
    eye_time=time-time(1);
    x1   =smooth3_b((x-(A.screenRect(3)/2))/A.pixperdeg);
    y1   =smooth3_b((y-(A.screenRect(4)/2))/A.pixperdeg);
    shrinkage=abs([0;diff(size)]);
    s_shrinkage=smooth5_b(shrinkage);
    
    vel_x=[0; diff(x1)./diff(eye_time/1000)];
    vel_y=[0; diff(y1)./diff(eye_time/1000)];
    speed=sqrt(vel_x.^2+vel_y.^2);
    % clf;hold on;axis auto
    % plot(x1,'.-b')
    % plot([0;diff(x1)],'.-c')
    % plot(y1,'.-r')
    % plot([0;diff(y1)],'.-m')
    % plot(speed,'.-g')
    % plot(find(speed>1000),speed(speed>1000),'.y')
    
    clear blink;    blink(length(eye_time))=0;
    blink(size<mean(size)-(2*std(size)))=1;
    blink(shrinkage>50)=1;     %blink(shrinkage>(mean(shrinkage)+(1*std(shrinkage))))=1;
    blink(s_shrinkage>50)=1;   %blink(s_shrinkage>(mean(s_shrinkage)+(1*std(s_shrinkage))))=1;
    blink(find((abs(x1)>40|abs(y1)>40)))=1;
    blink(speed>900)=1;
    blink(end)=0;
    s_blink01=smooth5_b(blink);
    s_blink02=smooth5_b(round(s_blink01+.25));
    blink=round(s_blink02+.25)';
    
    if redraw
        fig(50);clf;
        set(50,'Position',[5 (scnsize(4)*.6)+30 scnsize(3)-8 round(scnsize(4)*.3) ],'name',mat_file,'NumberTitle','off');
        set(gca,'Position',[ .05 .11 .9 .81]);hold on;tickout
        
        cla;
        clear blink;    blink(length(eye_time))=0;
        h_blink=plot(eye_time,blink*1000);
        
        % SIZE
        h_size=plot(eye_time,size,'.-','color',[1 .7 0]);
        blink(size<(mean(size )-(2*std(size ))))=1;
        hline(mean(size)-(2*std(size)),[1 .7 0])
        delete(h_blink);h_blink=plot(eye_time,blink*1000)
        %SHRINKAGE
        h_shrink=plot(eye_time,shrinkage,'.-','color',[.8 .8 .8]);
        hline(50,[.8 .8 .8])
        blink(shrinkage>50)=1;
        delete(h_blink);h_blink=plot(eye_time,blink*1000)
        %SPEED
        h_speed=plot(eye_time,speed/10,'.-g');
        hline(900/10,'-.g')
        blink(speed>900)=1;
        delete(h_blink);h_blink=plot(eye_time,blink*1000)
        %POSITION
        plot(eye_time,x1,'.-b');
        plot(eye_time,y1,'.-r');
        blink(find((abs(x1)>40|abs(y1)>40)))=1;
        delete(h_blink);h_blink=plot(eye_time,blink*1000)
        
        plot(eye_time(~~blink),x1(~~blink),'.c');
        plot(eye_time(~~blink),y1(~~blink),'.m');
        axis tight
        hline(50/10);
        ylim([-50 100]);
        blink(end)=0;
        s_blink01=smooth5_b(blink);
        temp01=plot(eye_time,s_blink01*1000,'k')
        s_blink02=smooth5_b(round(s_blink01+.25));
        temp02=plot(eye_time,round(s_blink02+.25)*1000,'y')
        
        blink=round(s_blink02+.25)';
        delete(h_blink);h_blink=plot(eye_time,blink*1000)
        delete(temp01);
        delete(temp02)
        
    end  
    speed2=round(smooth5_b(speed));
    speed2(1)=1; % can't be zero and needs to be less than threshold
    speed2(end)=1; % can't be zero and needs to be less than threshold
    s_shrinkage(1)=1;% can't be zero and needs to be less than threshold
    s_shrinkage(end)=1;% can't be zero and needs to be less than threshold
    eye_x1=x1;
    eye_y1=y1;
    i=1;
    end_eye=[];
    start_eye=[];
    s_start_eye=[];
    start_blink=[];
    end_blink=[];
	while sum(diff(blink)==1)>0
        blink(end)=0;
        start_blink(i)=min(find(diff([0;blink])== 1)); % put a zero on each end to force end of saccade if it goes off the end of the block
        end_blink(i)  =min(find(diff([0;blink])==-1));
        if redraw
            xlim([eye_time(max([1 start_blink(i)-50])) eye_time(min([length(eye_time) end_blink(i)+50]))])
            ylim([-100 500])
            a=vline(eye_time([start_blink(i) end_blink(i)]),'y');	   
            pause(.2);
        end
        %if (max(speed2(start_blink(i): end_blink(i)))>800 & max(s_shrinkage(start_blink(i): end_blink(i)))>50) |max(speed2(start_blink(i): end_blink(i)))>1100
        if  any(size(start_blink(i): end_blink(i))==0) | sum((abs(x1(start_blink(i):end_blink(i)))>30|abs(y1(start_blink(i):end_blink(i)))>30))
%             [val loc]=max(speed(start_blink(i):end_blink(i)));
%             find_max=start_blink(i)+loc-1;		            
            if redraw
                delete(h_shrink);
                h_shrink=plot(eye_time,s_shrinkage,'.-','color',[.8 .8 .8]);
                delete(h_speed);
                h_speed=plot(eye_time,speed2/10,'.-g');
                delete(h_size)     
                h_size=plot(eye_time,size,'.-','color',[1 .7 0]);
            end
            %%%%%%%%%%%%%%min speed limit is set to 15 for london
            %%%%%%%%%%%%%%min speed limit is set to 25 for eyelink2
            min_speed=25;
            p=50;
            min_range=max([1;start_blink(i)-p]);
            while ~any( speed2(min_range:start_blink(i))>0 & s_shrinkage(min_range:start_blink(i))<=10 )   & min_range>1
                p=p+50;
                min_range=max([1;start_blink(i)-p]);
            end
            start_blink2(i)=(max(find(speed2(min_range:start_blink(i)  )>0 & s_shrinkage(min_range:start_blink(i)  )<=10 ))+min_range -1);
            
            p=50;
            max_range=min([end_blink(i)+p length(speed2)]);
            while ~any( speed2(  end_blink(i):max_range)>0 & s_shrinkage(end_blink(i):max_range)<=10 ) & max_range<length(speed2)
                p=p+50;
                max_range=min([end_blink(i)+p length(speed2)]);
            end
            clear p;
            end_blink2(i)  =(min(find( speed2(  end_blink(i):max_range)>0 & s_shrinkage(end_blink(i):max_range)<=10 ))+end_blink(i)-1);
%             while ~any(speed2(min_range:start_blink(i)) < min_speed & speed2(min_range:start_blink(i))>0 & s_shrinkage(min_range:start_blink(i))<=10 )   & min_range>1
%                 p=p+50;
%                 min_range=max([1;start_blink(i)-p]);
%             end
%             start_blink2(i)=(max(find(speed2(min_range:start_blink(i)) < min_speed & speed2(min_range:start_blink(i))>0 & s_shrinkage(min_range:start_blink(i))<=10 ))+min_range  -1);
%             
%             p=50;
%             max_range=min([end_blink(i)+p length(speed2)]);
%             while ~any(speed2(  end_blink(i):max_range)<min_speed & speed2(  end_blink(i):max_range)>0 & s_shrinkage(end_blink(i):max_range)<=10 ) & max_range<length(speed2)
%                 p=p+50;
%                 max_range=min([end_blink(i)+p length(speed2)]);
%             end
%             clear p;
%             end_blink2(i)  =(min(find(speed2(  end_blink(i):max_range)<min_speed & speed2(  end_blink(i):max_range)>0 & s_shrinkage(end_blink(i):max_range)<=10 ))+end_blink(i)-1);
            
            if redraw
                b=vline(eye_time([start_blink2(i) end_blink2(i)]),'k');
                plot(eye_time(start_blink2(i)),x1(start_blink2(i)),'ob')
                plot(eye_time(start_blink2(i)),y1(start_blink2(i)),'or')
                plot(eye_time(end_blink2(i)),x1(end_blink2(i)),'ob')
                plot(eye_time(end_blink2(i)),y1(end_blink2(i)),'or')
            end
            range=(start_blink2(i):end_blink2(i));
            inc_x=diff(x1([range(1) range(end)]))/(length(range)-.999);
            inc_y=diff(y1([range(1) range(end)]))/(length(range)-.999);          
            %stupid thing... but only for one blink, in one file, in all of my data
            %does the above algorithm not work. so i made it .999
            %instead of 1                
            if inc_x
                x1(range)=(x1(range(1)):inc_x:x1(range(end)))';
            else
                x1(range)=x1(range(1));
            end
            if inc_y
                y1(range)=(y1(range(1)):inc_y:y1(range(end)))';
            else
                y1(range)=y1(range(1));
            end
            if redraw
                plot(eye_time(range),x1(range),'ob');
                plot(eye_time(range),y1(range),'or');
            end            
            % check to make sure that there are not two blinks in a row check            
            if blink(max([1 min(range(range>4))-5]))==6 %| blink(min(range(range>4))-3)==4 (4 is a non-blink) %check 5 points back
                blink(max(find(diff(blink(1:min(range)))==6))+1:max(range)-1)=1;
                speed2(max(3,min(range)-2):min(range))=100;
            else
                blink(range)=6;
                blink([min(range(range>1))-1 max(range)])=0;
            end
        else
            b=vline(0);
            start_blink2(i)=start_blink(i);
            end_blink2(i)=end_blink(i);

            blink(start_blink(i)+1:end_blink(i))=4;
            blink([start_blink(i) end_blink(i)])=0;
        end
        
        if redraw
            delete(h_blink)
            h_blink=hplot(eye_time,blink*50);     
            fig(51);clf;
            set(51,'Position',[5 (scnsize(4)*.25)+30 scnsize(3)-8 round(scnsize(4)*.3) ],'name',mat_file,'NumberTitle','off');
            subplot('Position',[0.690141 0.0857143 0.299296 0.814286]);hold on;axis square; axis([-20 20 -20 20])
            hold on;tickout;
            temp_range=([(max([1 start_blink2(i)-25])):(min([length(eye_time) end_blink2(i)+25]))]);
            plot(eye_x1(temp_range),eye_y1(temp_range),'.-r');
            plot(x1(min(temp_range):end_blink2(i)),y1(min(temp_range):end_blink2(i)),'o-');
            subplot('Position',[0.0334507 0.0761905 0.608275 0.814286]);hold on;
            plot(eye_time(temp_range),eye_x1(temp_range),'.-c')
            plot(eye_time(temp_range),eye_y1(temp_range),'.-m');
            plot(eye_time(start_blink2(i):end_blink2(i)),x1(start_blink2(i):end_blink2(i)),'.-b')
            plot(eye_time(start_blink2(i):end_blink2(i)),y1(start_blink2(i):end_blink2(i)),'.-r');
            axis tight; ylim([-30 30])
            fig(50);
            pause(1)
            fig(50); % again in case the user plays with the figs            
            delete(a)
            delete(b)
        end % redraw
        i=i+1;
    end
    if redraw
        axis auto
        ylim([-5 5])
    end % redraw
	
    fig(fp_num);
    set(fp_num,'Position',[5 (scnsize(4)*.6)+30 scnsize(3)-8 round(scnsize(4)*.3) ],'name',mat_file,'NumberTitle','off');
    clf;cla;hold on;tickout
    set(gca,'Position',[ .05 .11 .9 .81]);

    vel_x1=[0;diff(x1)./diff(eye_time/1000)];
    vel_y1=[0;diff(y1)./diff(eye_time/1000)];
    speed1=sqrt(vel_x1.^2+vel_y1.^2);
    %plot(eye_time,vel_x,'g');
    %plot(eye_time,vel_y,'y');
    plot(eye_time,s_shrinkage,'.-','color',[.8 .8 .8]);
    plot(eye_time,speed1,'.-g');
    plot(eye_time(blink>4),speed1(blink>4),'oy');
    plot(eye_time(blink>4),eye_x1(blink>4),'.-','color',[.7 .7 1]);
    plot(eye_time(blink>4),eye_y1(blink>4),'.-','color',[1 .7 .7]);
    plot(eye_time,x1,'.-b');
    plot(eye_time,y1,'.-r');
    plot(eye_time(blink>4),x1(blink>4),'.c');
    plot(eye_time(blink>4),y1(blink>4),'.m');
    plot(eye_time,blink*10,'k')
    h_size=plot(eye_time,size,'.-','color',[1 .7 0]);
    axis tight;ylim([-100 500])
	hline(50);
	
    if ~isfield(A,'colors')% just for andrews old data
        A.colors=define_colors;
        A.colors.PRO=A.colors.GREEN;
        A.colors.ANTI=A.colors.RED;
        A.colors.BACKGROUND=A.colors.D_GREY        
    end
	% change the 32 based psychophysics toolbox colors into
	% the 0-1 based stuff for matlab 
	names = fieldnames(A.colors);
	for i=1:length(names)
		colors.(names{i})=A.colors.(names{i})/31;
	end
	
	B=A;
    B.name=eye_file(1:length(eye_file)-4);
    B.colors=colors;
    B.eye_x=x1;
    B.eye_x_raw=eye_x1;
    B.eye_y=y1;
    B.eye_y_raw=eye_y1;
    B.vel_x=vel_x1;
    B.vel_y=vel_y1;
    B.speed=speed1;
    B.time=eye_time;
    B.blink=blink;

    save([B.name 'B.mat'],'B')
end %for fp_num

disp('eyelink2_blink_remover')

